﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/

using Microsoft.AspNetCore.Components;
using SupperTreeSample.Shared.Data;

namespace SupperTreeSample.Shared.Components;

/// <summary>
/// 
/// </summary>
public partial class EditFood
{
    [Parameter]
    public Food? Value { get; set; }

    [Parameter]
    public Func<Food, Task>? OnValueChanged { get; set; }

    [NotNull]
    private IEnumerable<string>? Items { get; set; }

    [NotNull]
    private string? FoodName { get; set; }

    [NotNull]
    private List<Food>? Foods { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        FoodName = Value?.Name;
        Foods = FoodGenerator.GenerateFoods();
        Items = Foods.Select(f => f.Name);
    }

    private async Task OnFoodChanged(string name)
    {
        // 匹配到当前菜品
        Value = Foods.FirstOrDefault(f => f.Name == name);
        if (OnValueChanged != null && Value != null)
        {
            await OnValueChanged(Value);
        }
    }

    private async Task OnIngredientChanged(Food food)
    {
        Value = food;
        if (OnValueChanged != null && Value != null)
        {
            await OnValueChanged(Value);
        }
    }

    private Task<IEnumerable<string>> OnFilter(string name)
    {
        // 从数据库或者内存中检索符合条件的菜品
        var items = string.IsNullOrEmpty(name)
            ? Foods.Select(f => f.Name)
            : Foods.Where(f => f.Name.Contains(name, StringComparison.OrdinalIgnoreCase)).Select(f => f.Name);
        return Task.FromResult(items);
    }
}
